uniform mat4 mvp;
uniform vec4 alightpos;
uniform vec4 alightpos2;
uniform vec4 aeyepos;
uniform float aradius;
uniform float aradius2;
attribute vec4 SATT_POSITION;
attribute vec2 SATT_TEXCOORD0;
attribute vec3 SATT_NORMAL;
//attribute vec3 SATT_TANGENT;
//attribute vec3 SATT_BITANGENT;
attribute vec4 SATT_TANGENT4F;

varying vec2 texcoord;
varying vec3 normal, tangent, bitangent;
varying vec4 tangent4f;
varying vec4 lightDir, halfAngle, eyeDir;
varying vec4 lightDir2, halfAngle2;
varying float att, att2;
//varying float test;

void calcAttenuation(in vec4 lightpos, in vec4 pos, in float radius, inout float att)
{
   float dist = length(lightpos  - pos);
   att = max( 0.0, (radius - dist)/radius );
}

void calcSpecularVariable(in mat4 transform, in vec4 pos, in vec4 lightpos, in vec4 eyeDir, inout vec4 alightDir, inout vec4 ahalfAngle)
{
   alightDir = normalize( lightpos  - pos );
   ahalfAngle = alightDir + eyeDir;

   ahalfAngle = ahalfAngle * transform;
   alightDir = alightDir * transform;
}

void main()
{
   gl_Position = mvp
                 * SATT_POSITION;
   //gl_Position = gl_ModelViewProjectionMatrix 
   //              * gl_Vertex;

   texcoord = vec2(SATT_TEXCOORD0);

   normal = normalize(SATT_NORMAL);
   //tangent = normalize(SATT_TANGENT);
   //bitangent = normalize(SATT_BITANGENT);
   tangent4f = SATT_TANGENT4F;

   // calc bitangent
   bitangent = cross(tangent4f.xyz, normal) * tangent4f.w;
   bitangent = normalize( bitangent );

   calcAttenuation(alightpos, SATT_POSITION, aradius, att);
   calcAttenuation(alightpos2, SATT_POSITION, aradius2, att2);

   //transform = mat4( tangent.x, tangent.y, tangent.z, 0.0f, 
	//				bitangent.x, bitangent.y, bitangent.z, 0.0f, 
	//				normal.x, normal.y, normal.z, 0.0f, 
	//				0.0f, 0.0f, 0.0f, 1.0f );
	
   //mat4 transform = mat4(vec4(tangent, 0.0), vec4(bitangent, 0.0), vec4(normal, 0.0), vec4(0.0, 0.0, 0.0, 1.0));
   mat4 transform = mat4(vec4(tangent4f.xyz, 0.0), vec4(bitangent, 0.0), vec4(normal, 0.0), vec4(0.0, 0.0, 0.0, 1.0));
   eyeDir = normalize( aeyepos  - SATT_POSITION );

   calcSpecularVariable(transform, SATT_POSITION, alightpos, eyeDir, lightDir, halfAngle);
   calcSpecularVariable(transform, SATT_POSITION, alightpos2, eyeDir, lightDir2, halfAngle2);
   
   eyeDir = eyeDir * transform;
   //eyeDir = normalize(eyeDir * transform);

   //test = tangent4f.w;
}
